<template>
  <div class="page-container">
    <!-- 顶部标题 -->
    <div class="header">
       <button class="back-button" @click="goBack" title="返回">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="header-content">
            <h1>报警历史</h1> <!-- Changed Title -->
        </div>
        <!-- Placeholder to balance the back button -->
        <div class="header-placeholder"></div>
    </div>

    <!-- 报警记录列表区域 -->
    <div class="content">
      <!-- 加载状态 (可选) -->
      <div v-if="isLoading" class="loading-indicator">
        正在加载...
      </div>
      <!-- 错误信息 (可选) -->
      <div v-else-if="errorMsg" class="error-message">
        {{ errorMsg }}
      </div>
      <!-- 无记录提示 -->
      <div v-else-if="alarmRecords.length === 0" class="no-records">
        暂无报警记录
      </div>
      <!-- 报警列表 -->
      <div v-else class="history-list">
        <div v-for="(record, index) in alarmRecords" :key="record.id || index" class="history-item alarm-item">
          <div class="alarm-details">
            <span class="record-datetime">{{ formatDateTime(record.timestamp) }}</span>
            <span class="alarm-message">{{ record.message }}</span>
            <span class="alarm-type">类型: {{ record.type || '未知' }}</span>
          </div>
          <!-- 可以根据需要添加操作按钮，例如查看详情 -->
          <!-- <button class="view-button" @click="viewAlarmDetails(record)">详情</button> -->
        </div>
      </div>
    </div>

    <!-- 底部导航组件 -->
    <navigation :active-tab="activeTab" @tab-change="handleTabChange" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import Navigation from '@/components/Navigation.vue';
import axios from 'axios'; // 如果需要API调用
import { getItem } from '@/components/Session.vue';

export default {
  components: {
    Navigation
  },
  setup() {
    const router = useRouter();
    const activeTab = ref('mine'); // 假设从个人中心进入，保持'mine'激活
    const alarmRecords = ref([]); // 存储报警记录列表
    const isLoading = ref(false); // 加载状态
    const errorMsg = ref(''); // 错误消息状态

    const user = ref(getItem('user'));
    // --- 数据获取 ---
    const fetchAlarmHistory = async () => {
      isLoading.value = true;
      errorMsg.value = '';
      alarmRecords.value = [];
      console.log("开始获取报警历史...");

      try {
        const response = await axios.get('/api/alert/history', {params:{
          username: user.value.username
        }});
        if (response.data.code === 200 && Array.isArray(response.data.data)) {
          alarmRecords.value = response.data.data.map(item => ({
            id: item.id,
            timestamp: new Date(item.time).getTime(),
            message: `${item.indicatorName}异常 (${item.value})`,
            type: item.indicatorName
          }));
        } else {
          errorMsg.value = response.data.message || '加载失败';
        }
      } catch (error) {
        console.error('请求报警历史失败:', error);
        errorMsg.value = '网络错误，请稍后重试';
      } finally {
        isLoading.value = false;
      }
    };

    // --- 辅助函数 ---
    const formatDateTime = (timestamp) => {
      if (!timestamp) return '未知时间';
      const date = new Date(timestamp);
      // 返回 YYYY-MM-DD HH:MM:SS 格式
      return date.toLocaleString('sv-SE'); // 使用瑞典本地化格式得到 YYYY-MM-DD HH:MM:SS
    };

    // --- 导航与交互 ---
    // (如果添加了 "查看详情" 按钮，可以在这里实现)
    // const viewAlarmDetails = (record) => { ... };

    const goBack = () => {
      if (window.history.length > 1) {
           router.go(-1);
       } else {
           router.push('/personal'); // 默认返回个人中心页
       }
    };

    const handleTabChange = (newTab) => {
        activeTab.value = newTab;
        if (newTab === 'home') {
            router.push('/');
        } else if (newTab === 'mine') {
            // 如果已在 /personal 或其子页面，可能不需要重复导航
            if (router.currentRoute.value.path !== '/personal') {
                 router.push('/personal');
            }
        }
    };

    // --- 生命周期钩子 ---
    onMounted(() => {
      console.log('AlarmHistoryView 组件已挂载');
      fetchAlarmHistory(); // 组件挂载时获取历史记录
    });

    // --- 返回值 ---
    return {
      activeTab,
      alarmRecords,
      isLoading,
      errorMsg,
      goBack,
      handleTabChange,
      formatDateTime,
      // viewAlarmDetails, // 如果添加了详情功能
    };
  }
}
</script>

<style scoped>
/* Reuse styles from AdiviceHistoyRecordView.vue / EquipmentManagementView.vue */
.page-container {
  min-height: 100vh;
  max-width: 100vw;
  width: 100%;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow-x: hidden;
  padding-bottom: 15vw; /* Match Navigation height */
  box-sizing: border-box;
}

.header {
  background: linear-gradient(135deg, #4CAF50, #2196F3);
  color: white;
  padding: 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
  box-sizing: border-box;
}

.back-button {
  background: none;
  border: none;
  color: white;
  font-size: 5vw;
  cursor: pointer;
  padding: 2vw;
  margin-left: -2vw;
  line-height: 1;
  min-width: 10vw;
}

.back-button:hover {
  opacity: 0.8;
}

.header-content {
  text-align: center;
  flex-grow: 1;
}

.header-content h1 {
  font-size: 4.5vw;
  margin: 0;
  font-weight: 600;
}

.header-placeholder {
  width: 10vw;
  visibility: hidden;
}


.content {
  flex: 1;
  padding: 4vw;
  overflow-y: auto;
}

.no-records {
  text-align: center;
  color: #666;
  font-size: 3.5vw;
  padding-top: 10vw;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

.history-item {
  background: white;
  border-radius: 3vw;
  padding: 3vw 4vw;
  display: flex;
  justify-content: space-between;
  align-items: flex-start; /* Align items to top */
  box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.05);
}

/* Specific styles for alarm items */
.alarm-item {
  border-left: 5px solid #f44336; /* Red border for emphasis */
  padding-left: calc(4vw - 5px);
}

.alarm-details {
  display: flex;
  flex-direction: column;
  gap: 1vw;
  flex-grow: 1; /* Allow details to take space */
}

.record-datetime {
  font-size: 3.5vw; /* Slightly smaller for datetime */
  color: #555;
  font-weight: 500;
}

.alarm-message {
    font-size: 3.8vw;
    color: #333;
    font-weight: 600; /* Make message bold */
    line-height: 1.4;
}

.alarm-type {
    font-size: 3.2vw;
    color: #777;
    margin-top: 0.5vw;
}

/* Optional: Style for a details button if added */
.view-button {
  background-color: #2196F3; /* Blue button for details */
  color: white;
  border: none;
  border-radius: 1.5vw;
  padding: 1.5vw 3vw;
  font-size: 3.2vw;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-left: 2vw; /* Space between details and button */
  align-self: center; /* Center button vertically */
}

.view-button:hover {
  background-color: #1976D2;
}


/* Loading and Error styles */
.loading-indicator, .error-message {
  text-align: center;
  padding: 10vw 4vw;
  color: #666;
  font-size: 3.8vw;
}

.error-message {
  color: #EF4444; /* Red color for errors */
}

/* Responsive Adjustments (similar to other history views) */
@media screen and (max-width: 320px) {
  .page-container {
    padding-bottom: 18vw;
  }
  .header {
      padding: 3vw;
  }
  .back-button {
      font-size: 6vw;
  }
  .header-content h1 {
      font-size: 5vw;
  }
  .header-placeholder {
      width: 12vw;
  }
  .content {
    padding: 3vw;
  }
  .history-item {
    padding: 2.5vw 3vw;
    border-radius: 2.5vw;
     border-left-width: 4px;
     padding-left: calc(3vw - 4px);
  }
  .record-datetime {
      font-size: 3.2vw;
  }
   .alarm-message {
      font-size: 3.5vw;
  }
   .alarm-type {
      font-size: 3vw;
  }
   .view-button {
      padding: 1.2vw 2.5vw;
      font-size: 3vw;
      border-radius: 1.2vw;
  }
  .no-records, .loading-indicator, .error-message {
      font-size: 3.2vw;
  }
}
</style>


